package com.ts.api.module.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.DigestType;
import com.gitee.apanlh.util.algorithm.digest.DigestUtils;
import com.gitee.apanlh.util.algorithm.digest.HMac;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.encode.Base64Utils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.log.LogLevel;
import com.gitee.apanlh.util.net.http.HttpClientBuilder;
import com.gitee.apanlh.util.net.http.HttpResponse;
import com.gitee.apanlh.util.net.http.auth.HttpAuth;
import com.gitee.apanlh.util.net.http.auth.HttpAuthCustom;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.http.HttpMethod;
import com.ts.api.module.common.entity.bo.IpInfoBO;
import com.ts.api.module.common.service.IpInfoService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

@Service
public class IpInfoServiceImpl implements IpInfoService {

    /**
     *  签名
     *
     *  @param  secretId
     *  @param  secretKey
     *  @param  datetime
     *  @return String
     */
    private static String calcAuthorization(String secretId, String secretKey, String datetime) {
        String signStr = "x-date: " +  datetime;

        HMac hmac = DigestUtils.hmac(secretKey, DigestType.HMAC_SHA1);
        byte[] hash = hmac.digest(signStr);

        String sig = Base64Utils.encodeToStr(hash);
        String auth = "{\"id\":\"" + secretId + "\", \"x-date\":\"" + datetime + "\", \"signature\":\"" + sig + "\"}";
        return auth;
    }

    @Override
    public IpInfoBO getByIp(String ip) {
        String url = "https://ap-shanghai.cloudmarket-apigw.com/services-an5lqg09m/api/ip/query";
        String secretId = "Q71gCKe73B3OEKPD";
        String secretKey = "D2LPCSYnttyUSlEIcW4w0emMDZhFQQJ0";

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String datetime = sdf.format(cd.getTime());

        //  签名
        String auth = calcAuthorization(secretId, secretKey, datetime);
        HttpAuthCustom authorization = HttpAuth.custom("Authorization", auth);

        //  发送
        HttpResponse build = HttpClientBuilder.builder(url, HttpMethod.POST)
                .withAuth(authorization)
                .withQueryParams(newMap -> {
                    newMap.put("ip", ip);
                    newMap.put("request-id", IdUtils.getSimpleUuid());
                })
                .withLogLevel(LogLevel.WARN)
                .withErrorLogLevel(LogLevel.WARN)
                .build();

        String resultJson = build.getStr();

        JSONObject jsonObject = JsonUtils.get(resultJson);
        JSONObject result = jsonObject.getJSONObject("data");
        if (ValidParam.isNotNull(result)) {
            return result.toJavaObject(IpInfoBO.class);
        }
        return null;
    }
}
